﻿using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;

namespace MerchantGalaxyGuide
{
    public class GalaxyMathRules
    {
        private static readonly char[] RepeatableChars = new char[] { 'I', 'X', 'C', 'M' };
        private static readonly char[] UnRepeatableChars = new char[] { 'D', 'L', 'V'};

        public bool LegalCharsCheck(string numberString)
        {
            foreach (var ch in numberString)
            {
                if(RepeatableChars.Contains(ch)||UnRepeatableChars.Contains(ch))
                    continue;
                else
                    return false;
            }
            return true;
        }

        public bool RepeatSquenceCheck(string numberString)
        {
            if (numberString == string.Empty)
                return false;
            int repeatTimes = 0;
            
            char lastChar = numberString[0];
            int currentIndex = 1;
            while(currentIndex<numberString.Length)
            {
                char currentChar = numberString[currentIndex];
                if (lastChar == currentChar)
                {
                    if (RepeatableChars.Contains(currentChar))
                    {
                        repeatTimes++;
                    }
                    else
                    {
                        return false; //unrepeatable chars repeat
                    }
                    if (repeatTimes > 3)
                    {
                        return false;
                    }
                }
                else//different chars
                {
                    repeatTimes = 1;
                    lastChar = currentChar;
                }
                currentIndex++;
            }
            return true;
        }

        public int CalculateValue(List<int> intSequence)
        {
            if(intSequence==null)
                throw new Exception("Can not put Null to caculate.");
            if (intSequence.Count == 0)
                return 0;
            if (intSequence.Count == 1)
                return intSequence[0];
            int result = 0;
            int current = 0;
            int next = 1;
            int currentValue=0;
            int nextValue=0;
            while (next < intSequence.Count)
            {
                currentValue = intSequence[current];
                nextValue = intSequence[next];
                if (currentValue >= nextValue)
                    result += currentValue;
                else
                    result -= currentValue;
                current++;
                next++;
                
            }
            result += nextValue;
            return result;
        }
    }
}
